package com.ai.databao.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;

import net.sf.json.JSONObject;

/* *
 *类名：AlipayFunction
 *功能：支付宝接口公用函数类
 *详细：该类是请求、通知返回两个文件所调用的公用函数核心处理文件，不需要修改
 *版本：3.3
 *日期：2012-08-14
 *说明：
 *以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
 */

public class AlipayCore {
	private final static Logger logger=LoggerFactory.getLogger(AlipayCore.class);
	
	/**
	  * http请求对端方法,POST请求,微信等接口：退款、扫码接口等使用,http post访问,使用 new URL(urls)
	    * 
	    */
	public static String HttpUrl_Post_Request(String urls,String parm) {
	        String inputLine = "";
	        HttpURLConnection urlConnection=null;
	        try {
	        	URL url = new URL(urls);
	            urlConnection = (HttpURLConnection) url.openConnection();
	            urlConnection.setDoOutput(true);
	            //设置连接主机超时（单位：毫秒）30秒
	            urlConnection.setConnectTimeout(30000);  
	            //设置从主机读取数据超时（单位：毫秒） 30秒
	            urlConnection.setReadTimeout(30000);  
	            urlConnection.setRequestProperty("Content-Length", Integer.toString(parm.length()));
	            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; text/html; charset=utf-8");
	            urlConnection.setRequestMethod("POST");
	            OutputStream outputStream = urlConnection.getOutputStream();
	            java.io.OutputStreamWriter outputSW = new OutputStreamWriter(outputStream, "utf-8");
	            outputSW.write(parm);
	            outputSW.flush();
	            outputSW.close();
	            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection
	                .getInputStream(),"utf-8"));
	            logger.info("HttpUrl_Post_Request----> in:"+in);
	            String context="";
	            while ( (context = (in.readLine())) != null) {
	            	inputLine+=context.trim();
	            }
	            logger.info("HttpUrl_Post_Request---->inputLine:"+inputLine+"    in:"+in);
	            in.close();
	            in=null;
	            outputSW=null;
	        } catch (Exception e) {
	        	logger.debug("HttpUrl_Post_Request---->e:"+e.getMessage());
	            e.printStackTrace();
	        }
	        finally{
	        	if(urlConnection!=null)
	        	urlConnection.disconnect();
	        	urlConnection=null;
	        	logger.debug("HttpUrl_Post_Request---->urls:"+urls+" parm:"+parm);
	        }
	        return inputLine;
	        
	    }
	/**
	  * http请求对端方法,POST请求,支付宝接口：退款、扫码接口等使用,http post访问,使用ssl模式
	    * 
	    */
	public static String Httpssl_Post_Request(String urls,String parm) {
	        String inputLine = "";
	        HttpURLConnection urlConnection=null;
	        try {
//	        	new com.sun.net.ssl.internal.www.protocol.https.Handler(),由于在weblogic部署使用此模式
	            URL url = new URL(null,urls,new com.sun.net.ssl.internal.www.protocol.https.Handler());
   	        if("https".equalsIgnoreCase(url.getProtocol())){
                   ignoreSsl();
               }
	            urlConnection = (HttpURLConnection) url.openConnection();
	            urlConnection.setDoOutput(true);
	            //设置连接主机超时（单位：毫秒）30秒
	            urlConnection.setConnectTimeout(30000);  
	            //设置从主机读取数据超时（单位：毫秒） 30秒
	            urlConnection.setReadTimeout(30000);  
	            urlConnection.setRequestProperty("Content-Length", Integer.toString(parm.length()));
	            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; text/html; charset=utf-8");
	            urlConnection.setRequestMethod("POST");
	            OutputStream outputStream = urlConnection.getOutputStream();
	            java.io.OutputStreamWriter outputSW = new OutputStreamWriter(outputStream, "utf-8");
	            outputSW.write(parm);
	            outputSW.flush();
	            outputSW.close();
	            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection
	                .getInputStream(),"utf-8"));
	            logger.info("Httpsll_Post_Request----> in:"+in);
	            String context="";
	            while ( (context = (in.readLine())) != null) {
	            	inputLine+=context.trim();
	            }
	            logger.info("Httpsll_Post_Request---->inputLine:"+inputLine+"    in:"+in);
	            in.close();
	            in=null;
	            outputSW=null;
	        } catch (Exception e) {
	        	logger.debug("Httpsll_Post_Request---->e:"+e.getMessage());
	            e.printStackTrace();
	        }
	        finally{
	        	if(urlConnection!=null)
	        	urlConnection.disconnect();
	        	urlConnection=null;
	        	logger.debug("Httpsll_Post_Request---->urls:"+urls+" parm:"+parm);
	        }
	        return inputLine;
	        
	    }
	private static void ignoreSsl() throws Exception{
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
    private static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
    private static class miTM implements TrustManager,X509TrustManager {

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }
        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
        
    }
    public static JSONObject parseString2Json(String data) throws Exception{
    	
    	if(!StringUtils.isEmpty(data)){
    		return JSONObject.fromObject(data);
    	}
    	return null;	
    }
    public static void main(String[] args) throws Exception {
    	String params = "key=75334e9a46df2c66b932ca23cba4fb5b&name=陈聚福&idCard=450802198704020517";
    	
    	String ret = "http://www.chinadatapay.com/interfaceInfo/interfaceDetails/1449";
    	System.out.println(ret.startsWith("https"));
    	String jsonstr = "{\"code\":10000,\"message\":\"成功\",\"data\":{\"inTime\": \"7\"}}";
    	JSONObject json = parseString2Json(jsonstr);
    	JSONObject data = (JSONObject) json.get("data");
    	System.out.println(data.get("inTime"));
	}
}
